package net.htjs.juc.sleepwait;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

/**
 * 保护性暂停模式
 * */
@Slf4j
public class Demo6 {

    private static final GuardeObject object = new GuardeObject();

    public static void main(String[] args) throws InterruptedException {
        GuardeObject guardeObject = new GuardeObject();
        new Thread(() -> {
            log.info("等待结果");
            List<String> lines = (List<String>) guardeObject.get(20000);
            log.info("结果是大小:{}", lines);
        }, "t1").start();

        new Thread(() -> {
            log.info("执行下载");
            try {
                List<String> lines = Downloader.download();
                //guardeObject.complete(lines);
                //虚假唤醒
                guardeObject.complete(null);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, "t2").start();
    }

    static class GuardeObject {
        private Object response;

        /**
         * //获取结果
         * 表示最多等多久
         * @param timeout
         * @return
         */
        public Object get(long timeout) {
            synchronized (this) {
                //开始时间
                long begin = System.currentTimeMillis();
                //经历的时间
                long passedTime = 0;
                while(response == null) {
                    //这一轮循环应该等待时间
                    long waitTime = timeout - passedTime;
                    //经历的时间超过了最大等待时间，退出循环
                    if(waitTime <= 0) {
                        break;
                    }
                    try {
                        this.wait(waitTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //求得经历时间
                    passedTime = System.currentTimeMillis() - begin;
                }
            }
            return response;
        }

        public void complete(Object response) {
            synchronized (this) {
                //给结果成员变量赋值
                this.response = response;
                this.notifyAll();
            }
        }
    }

}
